<?php

namespace Illuminate\View\Engines;

use Closure;
use InvalidArgumentException;

/**
 * 引擎解析器
 */
class EngineResolver
{
    /**
     * 引擎构造函数，其中每一个闭包都返回一个 Engine 接口的实例
     *
     * @var array
     */
    protected $resolvers = [];

    /**
     * 已构造成功的解析引擎对象缓存，每个元素都是一个 Engine 接口实例
     *
     * @var array
     */
    protected $resolved = [];

    /**
     * 注册一个新的引擎解析器，引擎字符串通常对应于文件扩展名
     *
     * @param  string $engine 引擎名称
     * @param  \Closure $resolver 引擎构造闭包
     * @return void
     */
    public function register($engine, Closure $resolver)
    {
        unset($this->resolved[$engine]);

        $this->resolvers[$engine] = $resolver;
    }

    /**
     * 按名称解析引擎实例
     *
     * @param  string $engine 引擎名称
     * @return \Illuminate\Contracts\View\Engine
     *
     * @throws \InvalidArgumentException
     */
    public function resolve($engine)
    {
        if (isset($this->resolved[$engine])) {
            return $this->resolved[$engine];
        }

        if (isset($this->resolvers[$engine])) {
            return $this->resolved[$engine] = call_user_func($this->resolvers[$engine]);
        }

        throw new InvalidArgumentException("Engine [{$engine}] not found.");
    }
}
